/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package net.openvision.util.xml;

import java.util.HashMap;
import java.util.Map;

import org.xml.sax.Attributes;

/**
 * Processes xml-elements by delegating the work to a collection of element
 * handlers, where each element handler is associated with one or more element
 * types.
 * 
 * @author Hannes Widmoser
 */
public class ElementHandlerMap implements ElementHandler {
	private Map<String, ElementHandler> elementHandlers;

	public ElementHandlerMap() {
		elementHandlers = new HashMap<String, ElementHandler>();
	}

	/**
	 * Associates the element handler with the given element name. Notice that
	 * one handler can be assigned to many elementNames by calling this method
	 * repeatedly with different element names but the same element handler
	 * instance. If the element handler does not support the element name this
	 * method does nothing.
	 * 
	 * @param elementName
	 *            one of the element names to which the handler should be
	 *            associated.
	 * @param handler
	 *            the element handler
	 */
	public void registerElementHandler(String elementName,
			ElementHandler handler) {
		if (handler.isSupported(elementName))
			elementHandlers.put(elementName, handler);
	}

	@Override
	public Object elementBegin(String elementName, Attributes attributes)
			throws UnknownElementException {
		ElementHandler handler = elementHandlers.get(elementName);
		if (handler != null) {
			return handler.elementBegin(elementName, attributes);
		} else {
			throw new UnknownElementException(elementName);
		}
	}

	@Override
	public void elementEnd(String elementName, Object parent)
			throws UnknownElementException {
		ElementHandler handler = elementHandlers.get(elementName);
		if (handler != null) {
			handler.elementEnd(elementName, parent);
		} else {
			throw new UnknownElementException(elementName);
		}
	}

	@Override
	public boolean isSupported(String elementName) {
		return elementHandlers.containsKey(elementName);
	}
}
